package com.itheima.itcasthealth.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.itcasthealth.common.Result;
import com.itheima.itcasthealth.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RestController
public class LoginController {

    @Autowired
    private HttpServletRequest req;

    @Autowired
    private MemberService userService;

    @PostMapping("/validateCode/send4Login.do")
    public Result sendMsg(String telephone) throws ClientException {

        Random random = new Random();
        int code = random.nextInt(900000)+100000;

        System.out.println("验证码:"+code);
        //SendSms.sendMsg(telephone,code+"");

        HttpSession session = req.getSession();
        session.setAttribute(telephone,code+"");

        return new Result(true,"生成验证码成功");
    }


    @PostMapping("/member/login.do")
    public Result login(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        if(validateCode == null){
            return new Result(false,"验证码为空");
        }

        HttpSession session = req.getSession();
        String code = (String) session.getAttribute(telephone);
        if (!code.equals(validateCode)){
            return new Result(false,"验证码不正确");
        }

        Result result = userService.login(telephone);

        if (result.isFlag()){

            session.setAttribute("user",result.getData());

        }


        return result;

    }
}
